package com.zhou.app.favourite.security.listener;

import com.zhou.app.favourite.security.EvictEvent;
import com.zhou.app.favourite.security.model.MyUserDetails;
import com.zhou.common.lib.util.StringUtils;
import com.zhou.common.operator.log.core.constant.OperateActionEnum;
import com.zhou.common.operator.log.core.model.ClientInfo;
import com.zhou.common.operator.log.core.model.OperateLogInfo;
import com.zhou.common.operator.log.core.model.PrincipalInfo;
import com.zhou.common.operator.log.core.service.OperateLogStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 被踢出去的listener
 * @author xianfeng
 * @date 2023/5/14 2:07
 */
@Slf4j
@Component
public class EvictEventListner {
    @Resource
    private OperateLogStorageService logService;

    @EventListener
    public void handleMyEventMap(EvictEvent evictEvent) {
        MyUserDetails currentUser = (MyUserDetails) evictEvent.getPrincipal();
        OperateLogInfo logInfo = new OperateLogInfo();
        logInfo.setAddTime(new Date());
        logInfo.setClientInfo(new ClientInfo());
        PrincipalInfo principalInfo = new PrincipalInfo();
        principalInfo.setUserId(currentUser.getUserId() + "");
        principalInfo.setUserName(currentUser.getUsername());
        principalInfo.setUserPhone(currentUser.getPhone());
        principalInfo.setOrgId(currentUser.getCurrOrgId() + "");
        principalInfo.setOrgName(currentUser.getCurrOrgName() + "");
        logInfo.setPrincipal(principalInfo);
        logInfo.setAction(OperateActionEnum.LOGIN.getAction());
        logInfo.setOperatingInstruction(
                StringUtils.format("登录成功:超过并发数量被踢出(后登录sessionId={})(前登录的sessionId={})"
                        , evictEvent.getKickSessionId(), evictEvent.getSessionId()));
        this.logService.append(logInfo);
    }
}
